<?php
if (! defined ( 'BASEPATH' ))
	exit ( 'No direct script access allowed' );
class Stock_model extends MY_Model {
	var $table = 'stock_assignment';
	
	// 构造函数
	public function __construct() {
		// 调用父类构造函数，必不可少
		parent::__construct ();
	}
	
	/**
	 * 添加供货商库存
	 *
	 * @param array $ddata        	
	 * @return boolean
	 */
	public function addStock($data, $uid) {
		try {
			$this->db->trans_begin ();
			
			// 获取address_id
			$result = $this->db->select ( 'address_id' )->from ( 'agent' )->where ( array (
					'id' => $uid 
			) )->get ()->row_array ();
			// 订单号
			mt_srand((double) microtime() * 1000000);
			$stock_num = '3' . str_pad($this->form_validation->address_id, 4, '0', STR_PAD_LEFT) . date('ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
			
			// 订单请求总数量
			$request_total_num = 0;
			$ids = array();
			foreach ( $data as $v ) {
				$ids[] = $v['product_id'];
				$request_total_num = $request_total_num + $v ['request_num'];
			}
			// 判断商品是否存在
			$idsCount = $this->db->from('product')->where_in('id', $ids)->count_all_results();
			if($idsCount !== count($ids)) {
				throw new Exception('10050');
			}
			// 插入订单
			$dataStock = array (
					'order_num' => $stock_num,
					'request_total_num' => $request_total_num,
					'address_id' => $result ['address_id'],
					'created_at' => time (),
					'status' => REST_Controller::STATUS_PROCESSING,
					'type' => '0',
					'agent_id' => $uid 
			);
			
			$this->db->insert ( 'stock_order', $dataStock );
			$stockOrderId = $this->db->insert_id ();
			
			foreach ( $data as $v ) {
				
				$dataInsert = array (
						'product_id' => $v ['product_id'],
						'request_number' => $v ['request_num'],
						'created_at' => time (),
						'order_id' => $stockOrderId,
						'dilivery_number' => '0',
						'actual_number' => $v ['request_num'] 
				);
				$res = $this->db->insert ( 'stock_assignment', $dataInsert );
				if (! $res) {
					throw new Exception ( '11201' );
				}
			}
			$this->db->trans_commit ();
			return true;
		} catch ( Exception $e ) {
			$this->db->trans_rollBack ();
			return intval($e->getMessage());
		}
	}
	
	/**
	 * 编辑入库
	 *
	 * @param array $data        	
	 * @throws Exception
	 * @return boolean
	 */
	public function addWareStock($orderid, $data, $identity) {
		try {
			$this->db->trans_begin ();
			
			// 获取address_id
			$result = $this->db->select ( 'address_id' )->from ( 'agent' )->where ( array (
				'id' => $identity['uid'] 
			) )->get ()->row_array ();
			
			$actual_total_num = 0;
			$time = time();
			foreach ( $data as $v ) {				
				// 更新库存真实数量
				$data = array(
					'actual_number' => $v['request_num'],
					'updated_at' => time()
				);
				$this->db->where ( array (
						'order_id' => $orderid,
						'product_id' => $v ['product_id'] 
				) );
				$this->db->update ( 'stock_assignment', $data);
				$actual_total_num += $v['request_num'];
				
				// 更新仓库库存数量，如果更新失败，就插入数据
				foreach ($identity['address_id'] as $address_id) {
					$this->db->set ( 'stock', "stock+{$v['request_num']}", false );
					$this->db->where ( array (
							'product_id' => $v ['product_id'],	
							'address_id' => $address_id
					) );
					$this->db->update ( 'sm_warehouse_stock' );
					$num = $this->db->affected_rows ();
					if ($num < 1) {
						$dataInsert = array (
								'product_id' => $v ['product_id'],
								'address_id' => $address_id,
								'stock' => $v ['request_num'],
								'updated_at' => $time
						);
						$this->db->insert ( 'sm_warehouse_stock', $dataInsert );
					}
				}	
			}
			// 更新订单状态
			$data = array (
				'actual_total_num' => $actual_total_num,
				'status' => REST_Controller::STATUS_ACTIVE,
				'updated_at' => time () 
			);
			$this->db->where ( array (
				'id' => $orderid,
				'address_id' => $result['address_id']
			) );
			$this->db->update ( 'stock_order', $data );
			$num = $this->db->affected_rows();
			if($num < 1) {
				throw new Exception('10005');
			}
			$this->db->trans_commit ();
			return true;
		} catch ( Exception $e ) {
			$this->db->trans_rollBack ();
			return intval($e->getMessage());
		}
	}
	
	/**
	 * 获取补货列表
	 */
	public function getStock($uid, $config, $type) {
		$limit = NULL;
		$offset = NULL;
		
		if (! empty ( $config )) {
			foreach ( $config as $key => $val ) {
				$$key = $val;
			}
		}
		
		// 获取address_id
		$result = $this->db->select ( 'address_id' )->from ( 'agent' )->where ( array (
				'id' => $uid 
		) )->get ()->row_array ();
		
		if ($limit && $offset >= 0) {
			$this->db->limit ( $limit, $offset );
		}
		
		$query = $this->db->select ( 'id as oid,order_num,created_at,status' )->from ( 'stock_order so' )->where ( array (
				'type' => $type,
				'address_id' => $result ['address_id'] 
		) )->order_by ( 'created_at', 'DESC' )->get ();
		$tmp = $query->result_array ();
		if (empty($tmp)) {
			return $tmp;
		}
		$tmp1 = array();
		foreach ($tmp as $v) {
			$tmp1 [$v ['oid']] = $v;
		}
		$query2 = $this->db->select ( 'order_id,product_id,name,request_number,actual_number as dilivery_number,price' )->from ( 'stock_assignment ta' )->join ( 'product p', 'p.id=ta.product_id', 'left' )
				->where_in('order_id', array_keys($tmp1))->get ();
		
		$tmp2 = $query2->result_array ();
		
		foreach ( $tmp2 as &$v ) {
			$order_id = $v ['order_id'];
			$v['price'] = number_format ( $v ['price'] / 100, 2 );
			if (isset($tmp1 [$order_id])) {
				$tmp1 [$order_id] ['details'] [] = $v;
			}
		}
		
		return array_values ( $tmp1 );
	}
	
	/**
	 * 退仓
	 *
	 * @param array() $data        	
	 * @param int $uid        	
	 */
	public function backStock($data, $uid) {
		try {
			$this->db->trans_begin ();
			
			// 获取address_id
			$result = $this->db->select ( 'address_id' )->from ( 'agent' )->where ( array (
					'id' => $uid 
			) )->get ()->row_array ();
			// 订单号
			mt_srand((double) microtime() * 1000000);
			$stock_num = '4' . str_pad($this->form_validation->address_id, 4, '0', STR_PAD_LEFT) . date('ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
			
			// 退仓请求总数量
			$request_total_num = 0;
			$ids = array();
			foreach ( $data as $v ) {
				$ids[] = $v['product_id'];
				$request_total_num = $request_total_num + $v ['request_num'];
			}
			// 判断商品是否存在
			$idsCount = $this->db->from('product')->where_in('id', $ids)->count_all_results();
			if($idsCount !== count($ids)) {
				throw new Exception('10050');
			}
			// 插入退订单
			$dataStock = array (
					'order_num' => $stock_num,
					'request_total_num' => $request_total_num,
					'address_id' => $result ['address_id'],
					'created_at' => time (),
					'status' => REST_Controller::STATUS_PROCESSING,
					'type' => '1',
					'agent_id' => $uid 
			);
			
			$this->db->insert ( 'stock_order', $dataStock );
			$stockOrderId = $this->db->insert_id ();
			
			foreach ( $data as $v ) {
				// 减少小仓库库存
				$this->db->set ( 'stock', "stock-{$v['request_num']}", false );
				$this->db->where ( array (
						'product_id' => $v ['product_id'],
						'address_id' => $result ['address_id'],
						'stock >=' => $v ['request_num'] 
				) );
				$this->db->update ( 'sm_warehouse_stock' );
				$num = $this->db->affected_rows ();
				
				if ($num < 1) {
					// 减少小仓库库存
					$this->db->set ( 'stock', "stock-{$v['request_num']}", false );
					$this->db->where ( array (
							'product_id' => $v ['product_id'],
							'address_id' => $result ['address_id'],
							'stock >=' => $v ['request_num'] 
					) );
					$this->db->update ( 'sm_warehouse_stock' );
				}
				
				$dataInsert = array (
						'product_id' => $v ['product_id'],
						'request_number' => $v ['request_num'],
						'created_at' => time (),
						'order_id' => $stockOrderId,
						'dilivery_number' => '0' 
				);
				$res = $this->db->insert ( 'stock_assignment', $dataInsert );
				if (! $res) {
					throw new Exception ( 'Syntax error' );
				}
			}
			$this->db->trans_commit ();
			return true;
		} catch ( Exception $e ) {
			$this->db->trans_rollBack ();
			return false;
		}
	}
	
	/**
	 * 获取库存列表
	 */
	public function getDiliver() {
	}
	
	/**
	 * 获取补仓单列表（即总仓库商品列表）
	 */
	public function getStockAll($config, $uid) {
		$limit = NULL;
		$offset = NULL;
		
		if (! empty ( $config )) {
			foreach ( $config as $key => $val ) {
				$$key = $val;
			}
		}
		
		// 获取address_id
		$result = $this->db->select ( 'address_id' )->from ( 'agent' )->where ( array (
				'id' => $uid 
		) )->get ()->row_array ();
		
		if ($limit && $offset >= 0) {
			$this->db->limit ( $limit, $offset );
		}
		$query = $this->db->select ( 'p.id,p.name,format(p.price/100,2) price,p.specs,p.stock as pstock,a.img', false )->from ( 'product p' )->where ( array (
				'p.status' => REST_Controller::STATUS_ACTIVE 
		) )->join ( 'album a', 'p.thumbnail_id=a.id', 'left' )->get ();
		$tmp = $query->result_array ();
		if (empty ( $tmp )) {
			return $tmp;
		}		
		$query2 = $this->db->select ( 'stock,product_id' )->from ( 'sm_warehouse_stock' )->where ( array (
				'address_id' => $result ['address_id'] 
		) )->get ();
		
		$tmp2 = $query2->result_array ();
		$tmp3 = array();
		foreach ($tmp2 as $v) {
			$tmp3[$v['product_id']] = $v;
		}
		foreach ( $tmp as &$v ) {
			$v['img'] = empty($v['img']) ? '' : base_url($v['img']);
			if (isset($tmp3[$v['id']])) {
				$v['stock'] = $tmp3[$v['id']]['stock'];
			} else {
				$v['stock'] = 0;
			}
		}
		
		return $tmp;
	}
	
	/**
	 * 取得该订单号下的商品列表
	 */
	public function getStockByNum($config, $num) {
		$limit = NULL;
		$offset = NULL;
		
		if (! empty ( $config )) {
			foreach ( $config as $key => $val ) {
				$$key = $val;
			}
		}
		
		if ($limit && $offset >= 0) {
			$this->db->limit ( $limit, $offset );
		}
		
		$query = $this->db->select ( 'ca.img,so.address_id,so.id as oid,so.order_num,so.created_at,so.status,ta.id as sid,ta.product_id,ta.request_number,ta.dilivery_number,p.name,p.price' )->from ( 'stock_order so' )->join ( 'stock_assignment ta', 'so.id=ta.order_id', 'left' )->join ( 'product p', 'ta.product_id=p.id', 'left' )->join ( 'album ca', 'ca.id=p.thumbnail_id' )->where ( array (
				'order_num' => $num 
		) )->get ();
		$tmp = $query->result_array ();
		if (empty ( $tmp )) {
			return $tmp;
		}
		
		$tmp1 = array ();
		foreach ( $tmp as $k => $v ) {
			$tmp1 [$v ['oid']] ['oid'] = $v ['oid'];
			$tmp1 [$v ['oid']] ['order_num'] = $v ['order_num'];
			$tmp1 [$v ['oid']] ['created_at'] = $v ['created_at'];
			$tmp1 [$v ['oid']] ['status'] = $v ['status'];
			$tmp1 [$v ['oid']] ['details'] [$k] ['sid'] = $v ['sid'];
			$tmp1 [$v ['oid']] ['details'] [$k] ['product_id'] = $v ['product_id'];
			$tmp1 [$v ['oid']] ['details'] [$k] ['request_number'] = $v ['request_number'];
			$tmp1 [$v ['oid']] ['details'] [$k] ['dilivery_number'] = $v ['dilivery_number'];
			$tmp1 [$v ['oid']] ['details'] [$k] ['name'] = $v ['name'];
			$tmp1 [$v ['oid']] ['details'] [$k] ['img'] = base_url ( $v ['img'] );
			$tmp1 [$v ['oid']] ['details'] [$k] ['price'] = number_format ( $v ['price'] / 100, 2 );
		}
		return array_values ( $tmp1 );
	}
	
	/**
	 * 取得网点管理员管理的仓库商品列表
	 */
	public function getStockByWD($config, $uid) {
		$limit = NULL;
		$offset = NULL;
		
		if (! empty ( $config )) {
			foreach ( $config as $key => $val ) {
				$$key = $val;
			}
		}
		
		if ($limit && $offset >= 0) {
			$this->db->limit ( $limit, $offset );
		}
		
		// 获取address_id
		$result = $this->db->select ( 'address_id' )->from ( 'agent' )->where ( array (
				'id' => $uid 
		) )->get ()->row_array ();
		
		$query = $this->db->select ( 'p.id,p.name,p.price,ws.stock,p.specs,a.img,ws.status' )->from ( 'sm_warehouse_stock ws' )->where ( array (
				'address_id' => $result ['address_id'] 
		) )->join ( 'product p', 'p.id=ws.product_id', 'left' )->join ( 'album a', 'p.thumbnail_id=a.id', 'left' )->get ();
		
		$tmp = $query->result_array ();
		
		foreach ( $tmp as $k => $v ) {
			$tmp [$k] ['id'] = $v ['id'];
			$tmp [$k] ['name'] = $v ['name'];
			$tmp [$k] ['price'] = number_format ( $v ['price'] / 100, 2 );
			$tmp [$k] ['stock'] = $v ['stock'];
			$tmp [$k] ['specs'] = $v ['specs'];
			$tmp [$k] ['status'] = $v ['status'];
			$tmp [$k] ['img'] = base_url ( $v ['img'] );
		}
		
		if (empty ( $tmp )) {
			return $tmp;
		}
		
		return $tmp;
	}
	
	/**
	 * 取消补仓（退仓）订单申请
	 *
	 * @param int $order_num        	
	 */
	public function cancelStock($order_num) {
		// 更新订单状态
		$data = array (
				'status' => '0',
				'updated_at' => time () 
		);
		$this->db->where ( array (
				'order_num' => $order_num,
				'status !=' => 3 
		) );
		$this->db->update ( 'stock_order', $data );
		
		$num = $this->db->affected_rows ();
		if ($num < 1) {
			return false;
		}
		
		return true;
	}
	
	/**
	 * 添入预警库存
	 */
	public function addWarnStock($product_id, $warn_number, $uid) {
		
		// 获取address_id
		$result = $this->db->select ( 'address_id' )->from ( 'agent' )->where ( array (
				'id' => $uid 
		) )->get ()->row_array ();
		
		// 更新库存中的预警值
		$data = array (
				'warn_stock' => $warn_number 
		);
		$this->db->where ( array (
				'product_id' => $product_id,
				'address_id' => $result ['address_id'] 
		) );
		return $this->db->update ( 'sm_warehouse_stock', $data );
	}
	
	/**
	 * 取得预警库存列表
	 */
	public function getStockWarn($config, $uid) {
		$limit = NULL;
		$offset = NULL;
		
		if (! empty ( $config )) {
			foreach ( $config as $key => $val ) {
				$$key = $val;
			}
		}
		
		if ($limit && $offset >= 0) {
			$this->db->limit ( $limit, $offset );
		}
		
		// 获取address_id
		$result = $this->db->select ( 'address_id' )->from ( 'agent' )->where ( array (
				'id' => $uid 
		) )->get ()->row_array ();
		
		$query = $this->db->select ( 'p.id,p.name,p.price,ws.stock,p.specs,a.img,ws.warn_stock' )->from ( 'sm_warehouse_stock ws' )->where ( array (
				'address_id' => $result ['address_id'] 
		) )->join ( 'product p', 'p.id=ws.product_id', 'left' )->join ( 'album a', 'p.thumbnail_id=a.id', 'left' )->get ();
		
		$tmp = $query->result_array ();
		
		$tmp2 = array ();
		
		foreach ( $tmp as $k => $v ) {
			if (intval ( $v ['stock'] ) <= intval ( $v ['warn_stock'] )) {
				$tmp2 [$k] ['id'] = $v ['id'];
				$tmp2 [$k] ['name'] = $v ['name'];
				$tmp2 [$k] ['price'] = number_format ( $v ['price'] / 100, 2 );
				$tmp2 [$k] ['stock'] = $v ['stock'];
				$tmp2 [$k] ['warn_stock'] = $v ['warn_stock'];
				$tmp2 [$k] ['specs'] = $v ['specs'];
				
				$tmp2 [$k] ['img'] = base_url ( $v ['img'] );
			}
		}
		
		$tmp3 = array ();
		foreach ( $tmp as $k => $v ) {
			if (intval ( $v ['stock'] ) > intval ( $v ['warn_stock'] )) {
				$tmp3 [$k] ['id'] = $v ['id'];
				$tmp3 [$k] ['name'] = $v ['name'];
				$tmp3 [$k] ['price'] = number_format ( $v ['price'] / 100, 2 );
				$tmp3 [$k] ['stock'] = $v ['stock'];
				$tmp3 [$k] ['warn_stock'] = $v ['warn_stock'];
				$tmp3 [$k] ['specs'] = $v ['specs'];
				
				$tmp3 [$k] ['img'] = base_url ( $v ['img'] );
			}
		}
		
		return array_merge ( $tmp2, $tmp3 );
		;
	}
	
	/**
	 * 取得达到库存预警值的数量
	 */
	public function getStockWarnNum($uid) {
		// 获取address_id
		$result = $this->db->select ( 'address_id' )->from ( 'agent' )->where ( array (
				'id' => $uid 
		) )->get ()->row_array ();
		
		$query = $this->db->select ( 'p.id,p.name,p.price,ws.stock,p.specs,a.img,ws.warn_stock' )->from ( 'sm_warehouse_stock ws' )->where ( array (
				'address_id' => $result ['address_id'] 
		) )->join ( 'product p', 'p.id=ws.product_id', 'left' )->join ( 'album a', 'p.thumbnail_id=a.id', 'left' )->get ();
		
		$tmp = $query->result_array ();
		
		$tmp2 = array ();
		$i = 0;
		foreach ( $tmp as $k => $v ) {
			if (intval ( $v ['stock'] ) <= intval ( $v ['warn_stock'] )) {
				$i ++;
			}
		}
		
		return $i;
	}
	
	/**
	 * 商品下架
	 */
	public function stockDownOrUp($product_id, $uid, $type) {
		// 获取address_id
		$result = $this->db->select ( 'address_id' )->from ( 'agent' )->where ( array (
				'id' => $uid 
		) )->get ()->row_array ();
		
		$data = array (
				'status' => $type,
				'updated_at' => time () 
		);
		$this->db->where ( array (
				'product_id' => $product_id,
				'address_id' => $result ['address_id'] 
		) );
		
		$this->db->update ( 'sm_warehouse_stock', $data );
		
		//记录上下架的操作
		
		$dataInsert = array (
				'product_id' => $product_id,
				'status' => $type,
				'type' => '2',
				'op_user_id' => $uid,
				'created_at' => time()
		);
		return $this->db->insert ( 'product_handle_log', $dataInsert );
	}
	
	/**
	 * 取得网点管理员管理的仓库商品列表
	 */
	public function getStockOrderStatus($config, $uid) {
		$limit = NULL;
		$offset = NULL;
		
		if (! empty ( $config )) {
			foreach ( $config as $key => $val ) {
				$$key = $val;
			}
		}
		
		if ($limit && $offset >= 0) {
			$this->db->limit ( $limit, $offset );
		}
		
		// 获取address_id
		$result = $this->db->select ( 'address_id' )->from ( 'agent' )->where ( array (
				'id' => $uid 
		) )->get ()->row_array ();
		
		$query = $this->db->select ( 'p.id,p.name,p.price,ws.stock,p.specs,a.img,ws.status' )->from ( 'sm_warehouse_stock ws' )->where ( array (
				'address_id' => $result ['address_id'] 
		) )->join ( 'product p', 'p.id=ws.product_id', 'left' )->join ( 'album a', 'p.thumbnail_id=a.id', 'left' )->order_by('ws.updated_at','desc')->get ();
		
		$tmp = $query->result_array ();
		
		$tmp2 = array ();
		$tmp3 = array ();
		
		foreach ( $tmp as $k => $v ) {
			if ($v['status'] == '10') {
				$tmp2 [$k] ['id'] = $v ['id'];
				$tmp2 [$k] ['name'] = $v ['name'];
				$tmp2 [$k] ['price'] = number_format ( $v ['price'] / 100, 2 );
				$tmp2 [$k] ['stock'] = $v ['stock'];
				$tmp2 [$k] ['specs'] = $v ['specs'];
				$tmp2 [$k] ['status'] = $v ['status'];
				$tmp2 [$k] ['img'] = base_url ( $v ['img'] );
			}
		}
		
		foreach ( $tmp as $k => $v ) {
			if ($v['status'] == '0') {
				$tmp3 [$k] ['id'] = $v ['id'];
				$tmp3 [$k] ['name'] = $v ['name'];
				$tmp3 [$k] ['price'] = number_format ( $v ['price'] / 100, 2 );
				$tmp3 [$k] ['stock'] = $v ['stock'];
				$tmp3 [$k] ['specs'] = $v ['specs'];
				$tmp3 [$k] ['status'] = $v ['status'];
				$tmp3 [$k] ['img'] = base_url ( $v ['img'] );
			}
		}
		
        return array_merge ( $tmp2, $tmp3 );
	}
}
